<template>
  <div class="bom-details-page">
    <!-- 标题 -->
    <div class="page-title">BOM详情</div>

    <!-- 顶部信息卡片 -->
    <el-card class="top-card" shadow="never">
      <div class="title-line">{{ bom.subject }}</div>
      <div class="meta-line">
        <span>创建人：{{ bom.creator || '-' }}</span>
        <span>创建时间：{{ bom.createdAt || '-' }}</span>
        <span>修改人：{{ bom.updatedBy || '-' }}</span>
        <span>修改时间：{{ bom.updatedAt || '-' }}</span>
      </div>
      <div class="actions">
        <el-button type="primary" @click="goEdit">编辑</el-button>
        <el-button @click="onPrint">打印</el-button>
        <el-button>删除</el-button>
        <el-button @click="openExplosion">BOM结构展开</el-button>
      </div>
    </el-card>

    <!-- 主信息卡片：Tabs -->
    <el-card class="main-card" shadow="never">
      <el-tabs v-model="activeTab">
        <el-tab-pane label="BOM信息" name="base">
          <div class="section">
            <div class="section-title">基础信息</div>
            <el-row :gutter="40" class="kv-grid">
              <el-col :span="12" class="kv-item">
                <span class="k">BOM编号：</span>
                <span class="v">{{ bom.code }}</span>
              </el-col>
              <el-col :span="12" class="kv-item">
                <span class="k">BOM主题：</span>
                <span class="v">{{ bom.subject }}</span>
              </el-col>

              <el-col :span="12" class="kv-item">
                <span class="k">默认BOM：</span>
                <span class="v">{{ bom.isDefault ? '是' : '否' }}</span>
              </el-col>
              <el-col :span="12" class="kv-item">
                <span class="k">版本：</span>
                <span class="v">{{ bom.version }}</span>
              </el-col>

              <el-col :span="12" class="kv-item">
                <span class="k">成品类型：</span>
                <span class="v">{{ bom.productType }}</span>
              </el-col>
              <el-col :span="12" class="kv-item">
                <span class="k">成品名称：</span>
                <span class="v">{{ bom.productName }}</span>
              </el-col>

              <el-col :span="12" class="kv-item">
                <span class="k">日产量：</span>
                <span class="v">{{ fmtNum(bom.dailyOutput) }}</span>
              </el-col>
              <el-col :span="12" class="kv-item">
                <span class="k">当前库存：</span>
                <el-popover placement="right" width="180" trigger="hover">
                  <template #reference>
                    <span class="v link">{{ fmtNum(bom.currentStock, 2) }} <el-icon class="caret"><ArrowDown /></el-icon></span>
                  </template>
                  <div class="stock-pop">
                    <div class="line"><span>本地：</span>{{ bom.stockDetail.local }}</div>
                    <div class="line"><span>仓库二：</span>{{ bom.stockDetail.w2 }}</div>
                    <div class="line"><span>仓库三：</span>{{ bom.stockDetail.w3 }}</div>
                    <div class="line"><span>物料备仓一：</span>{{ bom.stockDetail.buffer1 }}</div>
                    <div class="line"><span>新产品仓库：</span>{{ bom.stockDetail.newProd }}</div>
                  </div>
                </el-popover>
              </el-col>

              <el-col :span="12" class="kv-item">
                <span class="k">预估成本：</span>
                <span class="v">{{ fmtNum(bom.estimatedCost, 2) }}</span>
              </el-col>

              <el-col :span="24" class="kv-item">
                <span class="k">备注：</span>
                <span class="v">{{ bom.remark || '-' }}</span>
              </el-col>
            </el-row>
          </div>
        </el-tab-pane>

        <el-tab-pane label="BOM配件" name="parts">
          <div class="parts-toolbar">
            <div class="left">
              <el-button @click="exportParts">导出</el-button>
            </div>
            <div class="right">
              <el-input v-model="partsQuery" placeholder="按物品编码搜索" clearable style="width: 260px;" />
            </div>
          </div>

          <el-table :data="pagedParts" border stripe style="width: 100%" @selection-change="onPartSel">
            <el-table-column type="selection" width="48" />
            <el-table-column type="index" label="序号" width="60" />
            <el-table-column prop="itemCode" label="物品编码" min-width="120" />
            <el-table-column prop="itemName" label="物品名称" min-width="140" />
            <el-table-column prop="specModel" label="规格型号" min-width="160" />
            <el-table-column prop="unit" label="单位" width="80" />
            <el-table-column prop="brand" label="品牌" min-width="120" />
            <el-table-column prop="qty" label="配件数量" width="120" />
            <el-table-column prop="lossRate" label="损耗率" width="100">
              <template #default="{ row }">{{ row.lossRate != null ? row.lossRate + '%' : '-' }}</template>
            </el-table-column>
            <el-table-column prop="currentStock" label="当前库存" width="120" />
            <el-table-column prop="availableProduce" label="可供生产" width="120" />
            <el-table-column label="操作" width="120" fixed="right">
              <template #default>
                <el-button type="primary" link>创建子BOM</el-button>
              </template>
            </el-table-column>
            <template #empty>
              <div class="empty">暂无数据</div>
            </template>
          </el-table>

          <div class="pager">
            <div class="left">共{{ filteredParts.length }} 项数据</div>
            <div class="right">
              <el-select v-model="partsPageSize" size="small" style="width: 100px; margin-right: 8px;">
                <el-option :value="5" label="5条/页" />
                <el-option :value="10" label="10条/页" />
                <el-option :value="20" label="20条/页" />
              </el-select>
              <el-pagination
                background
                layout="prev, pager, next"
                :total="filteredParts.length"
                :page-size="partsPageSize"
                v-model:current-page="partsPage"
              />
            </div>
          </div>
        </el-tab-pane>
        <el-tab-pane label="工艺流程" name="route">
          <div class="route-toolbar">
            <div class="left">
              <el-button @click="exportRoutes">导出</el-button>
            </div>
            <div class="right">
              <el-input v-model="routesQuery" placeholder="按工艺编码搜索" clearable style="width: 260px;" />
            </div>
          </div>

          <el-table :data="pagedRoutes" border stripe style="width: 100%" @selection-change="onRouteSel">
            <el-table-column type="selection" width="48" />
            <el-table-column type="index" label="序号" width="60" />
            <el-table-column prop="routeCode" label="工艺编码" min-width="140" />
            <el-table-column prop="routeName" label="工艺名称" min-width="160" />
            <el-table-column prop="sort" label="排序" width="100" />
            <el-table-column label="关联时间" min-width="180">
              <template #default="{ row }">{{ fmtDateTime(row.selectedAt) }}</template>
            </el-table-column>
            <template #empty>
              <div class="empty">暂无数据</div>
            </template>
          </el-table>

          <div class="pager">
            <div class="left">共{{ filteredRoutes.length }} 项数据</div>
            <div class="right">
              <el-select v-model="routesPageSize" size="small" style="width: 100px; margin-right: 8px;">
                <el-option :value="5" label="5条/页" />
                <el-option :value="10" label="10条/页" />
                <el-option :value="20" label="20条/页" />
              </el-select>
              <el-pagination
                background
                layout="prev, pager, next"
                :total="filteredRoutes.length"
                :page-size="routesPageSize"
                v-model:current-page="routesPage"
              />
            </div>
          </div>
        </el-tab-pane>
        <el-tab-pane label="操作记录" name="logs">
          <div class="logs-toolbar">
            <div class="left">
              <el-button @click="exportLogs">导出</el-button>
            </div>
            <div class="right">
              <el-input v-model="logsQuery" placeholder="按操作人搜索" clearable style="width: 260px;" />
            </div>
          </div>

          <el-table :data="pagedLogs" border stripe style="width: 100%" @selection-change="onLogSel">
            <el-table-column type="selection" width="48" />
            <el-table-column type="index" label="序号" width="60" />
            <el-table-column prop="operator" label="操作人" min-width="120" />
            <el-table-column prop="operateTime" label="操作时间" min-width="180">
              <template #default="{ row }">{{ fmtDateTime(row.operateTime) }}</template>
            </el-table-column>
            <el-table-column prop="content" label="操作内容" min-width="160" />
            <template #empty>
              <div class="empty">暂无数据</div>
            </template>
          </el-table>

          <div class="pager">
            <div class="left">共{{ filteredLogs.length }} 项数据</div>
            <div class="right">
              <el-select v-model="logsPageSize" size="small" style="width: 100px; margin-right: 8px;">
                <el-option :value="5" label="5条/页" />
                <el-option :value="10" label="10条/页" />
                <el-option :value="20" label="20条/页" />
              </el-select>
              <el-pagination
                background
                layout="prev, pager, next"
                :total="filteredLogs.length"
                :page-size="logsPageSize"
                v-model:current-page="logsPage"
              />
            </div>
          </div>
        </el-tab-pane>
      </el-tabs>

      <div class="footer-actions">
        <el-button @click="goList">关闭</el-button>
      </div>
    </el-card>
  </div>
  <!-- BOM结构展开 抽屉 -->
  <el-drawer v-model="explodeVisible" title="BOM结构展开" size="40%" :with-header="true">
    <el-table :data="explodeRows" border stripe style="width: 100%" v-loading="explodeLoading">
      <el-table-column type="index" label="#" width="52" />
      <el-table-column prop="level" label="层级" width="64" />
      <el-table-column prop="itemCode" label="物料编码" min-width="120" />
      <el-table-column prop="itemName" label="物料名称" min-width="140" />
      <el-table-column prop="specModel" label="规格型号" min-width="160" />
      <el-table-column prop="unit" label="单位" width="80" />
      <el-table-column prop="brand" label="品牌" min-width="120" />
      <el-table-column prop="bomCode" label="BOM编码" min-width="120" />
      <el-table-column prop="version" label="版本" width="90" />
      <el-table-column label="单耗" width="100">
        <template #default="{ row }">{{ fmtNum(row.nodeQty) }}</template>
      </el-table-column>
      <el-table-column label="损耗率" width="90">
        <template #default="{ row }">{{ row.lossRate != null ? row.lossRate + '%' : '-' }}</template>
      </el-table-column>
      <el-table-column label="累计用量" width="120">
        <template #default="{ row }">{{ fmtNum(row.accQty) }}</template>
      </el-table-column>
      <template #empty>
        <div class="empty">暂无数据</div>
      </template>
    </el-table>
  </el-drawer>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { ArrowDown } from '@element-plus/icons-vue'
import { useRoute, useRouter } from 'vue-router'
import ERP from '@/utils/Interceptors'

const activeTab = ref('base')
const route = useRoute()
const router = useRouter()

// 详情数据占位：默认空，待对接接口加载
const bom = ref({
  subject: '',
  creator: '',
  createdAt: '',
  updatedBy: '',
  updatedAt: '',
  productCode: '',
  productName: '',
  code: '',
  isDefault: false,
  version: '',
  productType: '',
  dailyOutput: undefined as number | undefined,
  currentStock: 0,
  estimatedCost: '',
  remark: '',
  stockDetail: {
    local: 0,
    w2: 0,
    w3: 0,
    buffer1: 0,
    newProd: 0,
  },
})

// BOM配件
const parts = ref<Array<any>>([])
const partsQuery = ref('')
const partsPage = ref(1)
const partsPageSize = ref(10)
const filteredParts = computed(() => {
  const kw = (partsQuery.value || '').trim().toLowerCase()
  if (!kw) return parts.value
  return parts.value.filter((r:any) => (
    (r.itemCode || '').toLowerCase().includes(kw)
  ))
})
const pagedParts = computed(() => {
  const start = (partsPage.value - 1) * partsPageSize.value
  return filteredParts.value.slice(start, start + partsPageSize.value)
})
function onPartSel(_rows: any[]) {}
function exportParts() {
  // 简易导出：把当前过滤后的列表导出为 CSV
  const headers = ['序号','物品编码','物品名称','规格型号','单位','品牌','配件数量','损耗率','当前库存','可供生产']
  const rows = filteredParts.value.map((r:any, idx:number) => [
    idx + 1,
    r.itemCode ?? '',
    r.itemName ?? '',
    r.specModel ?? '',
    r.unit ?? '',
    r.brand ?? '',
    r.qty ?? '',
    r.lossRate != null ? `${r.lossRate}%` : '',
    r.currentStock ?? '',
    r.availableProduce ?? ''
  ])
  const csv = [headers.join(','), ...rows.map((a:any[]) => a.join(','))].join('\n')
  const blob = new Blob([csv], { type: 'text/csv;charset=utf-8;' })
  const url = URL.createObjectURL(blob)
  const a = document.createElement('a')
  a.href = url
  a.download = `BOM配件_${bom.value.code || ''}.csv`
  a.click()
  URL.revokeObjectURL(url)
}

// 工艺流程
const routes = ref<Array<any>>([])
const routesQuery = ref('')
const routesPage = ref(1)
const routesPageSize = ref(10)
const filteredRoutes = computed(() => {
  const kw = (routesQuery.value || '').trim().toLowerCase()
  if (!kw) return routes.value
  return routes.value.filter((r:any) => (
    (r.routeCode || '').toLowerCase().includes(kw)
  ))
})
const pagedRoutes = computed(() => {
  const start = (routesPage.value - 1) * routesPageSize.value
  return filteredRoutes.value.slice(start, start + routesPageSize.value)
})
function onRouteSel(_rows:any[]) {}
function exportRoutes() {
  const headers = ['序号','工艺编码','工艺名称','排序','关联时间']
  const rows = filteredRoutes.value.map((r:any, idx:number) => [
    idx + 1,
    r.routeCode ?? '',
    r.routeName ?? '',
    r.sort ?? '',
    fmtDateTime(r.selectedAt) ?? ''
  ])
  const csv = [headers.join(','), ...rows.map((a:any[]) => a.join(','))].join('\n')
  const blob = new Blob([csv], { type: 'text/csv;charset=utf-8;' })
  const url = URL.createObjectURL(blob)
  const a = document.createElement('a')
  a.href = url
  a.download = `工艺流程_${bom.value.code || ''}.csv`
  a.click()
  URL.revokeObjectURL(url)
}

// 操作记录
const logs = ref<Array<any>>([])
const logsQuery = ref('')
const logsPage = ref(1)
const logsPageSize = ref(10)
const filteredLogs = computed(() => {
  const kw = (logsQuery.value || '').trim().toLowerCase()
  if (!kw) return logs.value
  return logs.value.filter((r:any) => (
    (r.operator || '').toLowerCase().includes(kw)
  ))
})
const pagedLogs = computed(() => {
  const start = (logsPage.value - 1) * logsPageSize.value
  return filteredLogs.value.slice(start, start + logsPageSize.value)
})
function onLogSel(_rows:any[]) {}
function exportLogs() {
  const headers = ['序号','操作人','操作时间','操作内容']
  const rows = filteredLogs.value.map((r:any, idx:number) => [
    idx + 1,
    r.operator ?? '',
    fmtDateTime(r.operateTime) ?? '',
    r.content ?? ''
  ])
  const csv = [headers.join(','), ...rows.map((a:any[]) => a.join(','))].join('\n')
  const blob = new Blob([csv], { type: 'text/csv;charset=utf-8;' })
  const url = URL.createObjectURL(blob)
  const a = document.createElement('a')
  a.href = url
  a.download = `操作记录_${bom.value.code || ''}.csv`
  a.click()
  URL.revokeObjectURL(url)
}

// BOM结构展开
const explodeVisible = ref(false)
const explodeRows = ref<Array<any>>([])
const explodeLoading = ref(false)
async function openExplosion() {
  explodeVisible.value = true
  const id = route.query.id as string
  if (!id) { explodeRows.value = []; return }
  try {
    explodeLoading.value = true
    const { data } = await ERP.get(`/api/Boms/${id}/explode`)
    explodeRows.value = Array.isArray(data?.data) ? data.data : []
  } finally {
    explodeLoading.value = false
  }
}

function fmtNum(v:any, max:number = 4) {
  if (v === null || v === undefined || v === '') return ''
  const n = Number(v)
  if (Number.isNaN(n)) return String(v)
  // 初步去除尾随零
  let s = n.toString().replace(/(\.\d*?)0+$/, '$1').replace(/\.$/, '')
  // 若小数位仍然过长，进行截断到 max 位再去零
  if (s.includes('.')) {
    const [, frac = ''] = s.split('.')
    if (frac.length > max) {
      s = n.toFixed(max).replace(/(\.\d*?)0+$/, '$1').replace(/\.$/, '')
    }
  }
  return s
}

function fmtDateTime(v:any) {
  if (!v) return ''
  try {
    const d = new Date(v)
    if (Number.isNaN(d.getTime())) return String(v)
    const pad = (n:number)=> n.toString().padStart(2,'0')
    return `${d.getFullYear()}-${pad(d.getMonth()+1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}`
  } catch { return String(v) }
}

function goList() {
  router.push({ name: 'BOMList' })
}

function goEdit() {
  const id = route.query.id as string
  if (!id) return
  router.push({ name: 'BOMEdit', query: { id } })
}

function onPrint() {
  // 直接调用浏览器打印
  window.print()
}

onMounted(async () => {
  const id = route.query.id as string
  if (!id) return
  const { data } = await ERP.get(`/api/Boms/${id}`)
  const dto = data?.data || {}
  // 主信息
  bom.value.code = dto.code
  bom.value.subject = dto.subject
  bom.value.creator = dto.createdBy || ''
  bom.value.createdAt = fmtDateTime(dto.createdAt)
  bom.value.updatedBy = dto.updatedBy || ''
  bom.value.updatedAt = fmtDateTime(dto.updatedAt)
  bom.value.isDefault = dto.isDefault
  bom.value.version = dto.version
  bom.value.productType = dto.productType
  bom.value.productCode = dto.productCode
  bom.value.productName = dto.productName
  bom.value.dailyOutput = dto.dailyOutput
  bom.value.currentStock = dto.currentStock ?? 0
  bom.value.estimatedCost = dto.estimatedCost ?? ''
  bom.value.remark = dto.remark
  // 配件
  parts.value = dto.accessories || []
  // 工艺流程
  routes.value = Array.isArray(dto.processRoutes) ? dto.processRoutes : []
  // 操作记录
  logs.value = Array.isArray(dto.logs || dto.operationLogs) ? (dto.logs || dto.operationLogs) : []
})
</script>

<style scoped>
.bom-details-page {
  padding: 12px 12px 24px;
}
.page-title {
  font-size: 18px;
  font-weight: 600;
  margin-bottom: 12px;
}
.top-card {
  margin-bottom: 12px;
}
.title-line {
  font-size: 20px;
  font-weight: 600;
  margin-bottom: 6px;
}
.meta-line {
  color: #888;
  font-size: 13px;
  display: flex;
  flex-wrap: wrap;
  gap: 16px;
}
.actions {
  margin-top: 12px;
}
.main-card {
  margin-top: 12px;
}
.section {
  padding: 8px 4px 0 4px;
}
.section-title {
  position: relative;
  padding-left: 16px;
  margin-bottom: 8px;
  font-weight: 600;
}
.section-title::before {
  content: '•';
  position: absolute;
  left: 0;
  color: #409EFF;
}
.kv-grid {
  padding: 4px 8px 16px 8px;
}
.kv-item {
  margin: 6px 0;
  line-height: 28px;
}
.k {
  display: inline-block;
  width: 110px;
  color: #666;
}
.v {
  color: #333;
}
.v.link {
  cursor: default;
}
.caret {
  margin-left: 2px;
}
.stock-pop .line {
  display: flex;
  justify-content: space-between;
  margin: 4px 0;
}
.footer-actions {
  margin-top: 12px;
  text-align: center;
}
.parts-toolbar {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 10px;
}
.pager {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-top: 10px;
}
.route-toolbar {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 10px;
}
.route-toolbar .right {
  margin-left: 0;
}
.route-toolbar .right .el-input {
  width: 260px;
}
.logs-toolbar {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 10px;
}
</style>

<style>
@media print {
  /* 隐藏交互控件与抽屉 */
  .actions,
  .part-toolbar,
  .route-toolbar,
  .logs-toolbar,
  .el-pagination,
  .el-drawer,
  .el-dialog,
  .el-message,
  .el-notification,
  .el-upload,
  .el-upload__tip,
  .el-button { display: none !important; }

  /* 去除卡片阴影与边距，适配纸张 */
  .el-card { box-shadow: none !important; }
  .el-card__body { padding: 12px !important; }
  .main-card { margin-top: 10px !important; }

  /* 让表格在打印时更紧凑 */
  .el-table th, .el-table td { padding: 6px 8px !important; }

  /* 颜色保真 */
  body { -webkit-print-color-adjust: exact; print-color-adjust: exact; }
}
</style>